"""
    4月新增
"""
# _*_ coding:utf-8 _*_
import os
import sys
import unittest
import urllib3
import json
import ddt
import logging

from API.config import setting
from API.lib.readexcel import ReadExcel
from API.lib.sendrequests import sendRequests
from API.lib.dingding_debug import dingding_debug
from API.lib.writeexcel import WriteExcel

sys.path.append(os.path.dirname(os.path.dirname(__file__)))  # window环境适配的代码
# sys.path.append(os.path.abspath('..'))# linux环境适配的代码
urllib3.disable_warnings()
sheetnames = ["Sheet3"]
allData = []
for i in range(len(sheetnames)):
    allData += ReadExcel(setting.Source_File, sheetnames[i]).read_data(sheetnames[i])



@ddt.ddt
class Demo_API(unittest.TestCase):
    """轻诉App接口"""

    @classmethod
    def setUpClass(cls):
        # print("测试开始")
        # 初始化（只加载一次）
        cls.writer = WriteExcel(setting.Target_File, sheetnames[0])

    @ddt.data(*allData)
    def test_againdemoapi(self, data):
        # print('testNewApi开始测试---------------------------------')
        # 调用发送请求，获取响应判断，写入测试结果到表格
        # 1）获取数据
        # 获取ID字段数值，截取结尾数字并去掉开头0
        case_id = data['ID']
        rowNum = int(case_id.split("_")[2])
        # print("用例编号：", rowNum)
        casename = data['case_name']
        da_msg = data['msg']
        da_status = int(data['status_code'])
        # 写入表格
        OK_data = "PASS"
        NOT_data = "FAIL"
        # 2）发送请求，写入表格
        try:
            result = json.loads(sendRequests(data))
            re_status = result.get('status_code') or result.get('code')
            re_msg = result.get('msg') or result.get('message')
            # print("------------响应信息：", result)
            # 3）断言
            assert re_msg == da_msg, "状态码断言失败，响应code：{}，预期code：{}".format(
                    re_msg, da_msg)
            assert re_status == da_status, "状态码断言失败，响应code：{}，预期code：{}".format(
                    re_status, da_status)
            # 成功
            self.writer.write_data(rowNum + 1, OK_data)
        except Exception as e:
            # 断言失败
            logging.error("用例：{}，状态码断言失败，响应内容：{}，预期内容：{}".format(
                    rowNum,re_status, da_status))
            self.writer.write_data(rowNum + 1, NOT_data)
            # 发送钉钉通知
            dingding_debug(case_id, casename, data['url'], result, e)
            raise


    @classmethod
    def tearDownClass(cls):
        """测试类清理"""
        cls.writer.save()  # 统一保存excel处理结果
        # print("测试执行完成，保存文件")


if __name__ == "__main__":
    unittest.main()
